package com.gw.quotes.activity;

import android.os.Bundle;
import android.support.v4.app.FragmentTabHost;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TabHost.TabSpec;

import com.gw.quotes.R;
import com.gw.quotes.activity.fragment.BaseMainFragment;
import com.gw.quotes.activity.fragment.HomeFragment;
import com.gw.quotes.activity.fragment.MineFragment;
import com.gw.quotes.activity.fragment.OrderFragment;
import com.gw.quotes.activity.fragment.QuoteFragment;
import com.gw.quotes.activity.fragment.SortFragment;

public class MainActivity extends BaseFragmentActivity {

	// 定义FragmentTabHost对象
	private FragmentTabHost mTabHost;
	// 定义一个布局
	private LayoutInflater layoutInflater;
	// 定义数组来存放Fragment界面
	private Class fragmentArray[] = { HomeFragment.class, SortFragment.class,
			QuoteFragment.class, OrderFragment.class, MineFragment.class };
	// Tab选项卡的标签
	private String mTextviewArray[] = { "首页", "分类", "报价厅", "订单", "我的" };
	// 定义数组来存放按钮图片
	private int mImageViewArray[] = { R.drawable.bg_home, R.drawable.bg_sort,
			R.drawable.bg_quote, R.drawable.bg_order, R.drawable.bg_mine };

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		initView();
	}

	private void initView() {
		// 实例化布局对象
		layoutInflater = LayoutInflater.from(this);
		// 实例化TabHost对象，得到TabHost
		mTabHost = (FragmentTabHost) findViewById(R.id.ftabhost);
		mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);

		// 得到fragment的个数
		int count = fragmentArray.length;

		for (int i = 0; i < count; i++) {
			// 为每一个Tab按钮设置图标、文字和内容
			TabSpec tabSpec = mTabHost.newTabSpec(mTextviewArray[i])
					.setIndicator(getTabItemView(i));
			// 将Tab按钮添加进Tab选项卡中
			mTabHost.addTab(tabSpec, fragmentArray[i], null);
			// 设置Tab按钮的背景
			mTabHost.getTabWidget().getChildAt(i)
					.setBackgroundResource(R.drawable.bg_tabhost);
		}
	}

	private View getTabItemView(int index) {
		View view = layoutInflater.inflate(R.layout.item_tabhost, null);

		ImageView imageView = (ImageView) view.findViewById(R.id.imageview);
		imageView.setImageResource(mImageViewArray[index]);

		return view;
	}

	// 退出提示框
	public boolean dispatchKeyEvent(KeyEvent event) {

		if (event.getAction() == KeyEvent.ACTION_DOWN
				&& event.getKeyCode() == KeyEvent.KEYCODE_BACK
				&& event.getRepeatCount() == 0) {
			return ((BaseMainFragment) getSupportFragmentManager()
					.findFragmentByTag(mTabHost.getCurrentTabTag()))
					.dispatchKeyEvent(event);
		} else if (event.getKeyCode() != KeyEvent.KEYCODE_BACK) {
			return super.dispatchKeyEvent(event);
		}
		return false;
	}
}